package vip.xiaonuo.biz.modular.event.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.apilog.entity.DevApiLog;
import vip.xiaonuo.biz.modular.event.entity.BizEvent;
import vip.xiaonuo.biz.modular.event.entity.BizEventConfig;
import vip.xiaonuo.biz.modular.event.mapper.BizEventConfigMapper;
import vip.xiaonuo.biz.modular.event.mapper.BizEventMapper;
import vip.xiaonuo.biz.modular.event.service.BizEventReplaceService;
import vip.xiaonuo.biz.modular.event.service.BizEventWeighService;
import vip.xiaonuo.biz.modular.event.util.EventActionUtil;
import vip.xiaonuo.biz.modular.goods.entity.BizGoods;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsLedger;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsLedgerMapper;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsMapper;
import vip.xiaonuo.biz.modular.goods.result.GoodsLedgerPageResult;
import vip.xiaonuo.biz.modular.goods.service.BizGoodsService;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author 墨塵
 * @since 2023/4/25
 */
@Service
@Transactional
public class BizEventWeighServiceImpl implements BizEventWeighService {

    @Resource
    private BizGoodsMapper bizGoodsMapper;

    @Resource
    private BizEventConfigMapper bizEventConfigMapper;

    @Resource
    private BizEventReplaceService bizEventReplaceService;

    @Resource
    private BizEventMapper bizEventMapper;

    @Resource
    private BizGoodsLedgerMapper bizGoodsLedgerMapper;

    @Resource
    private BizGoodsService bizGoodsService;

    @Override
    public void handleWeigh(DevApiLog apiLog) {
        //获取物品信息
        BizGoods goods = bizGoodsMapper.getInfoByRfid(apiLog.getRfids());
        if (goods == null) {
            //未知试剂称重
            this.addRecordForReagentUnk(apiLog);
        } else {
            if (goods.getState() == 0) {
                //报废试剂称重
                this.addRecordForReagentScrap(goods, apiLog);
            }
            //出库称重异常
            this.addRecordForReagentUsageAbn(goods, apiLog);
            //与上次称重对比
            this.addRecordForReagentWeightThan(goods, apiLog);
            //更新试剂最后一次称重
            bizGoodsMapper.updateLastWeigh(goods.getId(), apiLog.getReagentWeight(), apiLog.getId());
            //首次称重
            if (goods.getReagentFirstWeigh() == null) {
                //更新第一次称重数据
                bizGoodsMapper.updateFirstWeigh(goods.getId(), apiLog.getReagentWeight(), apiLog.getId());
                if (goods.getReagentInitWeight() != null) {
                    //计算容器重量
                    bizGoodsService.handleReagentFistAvlData(goods, apiLog.getReagentWeight());
                }
            }
        }
    }

    /**
     * 未知试剂称重
     *
     * @param apiLog
     */
    private void addRecordForReagentUnk(DevApiLog apiLog) {
        //查询对应配置
        BizEventConfig eventConfig = bizEventConfigMapper.selectById("33");
        //事件描述
        String eventDesc = eventConfig.getEventDesc();
        eventDesc = eventDesc.replace("{{time}}", DateUtil.formatDateTime(DateUtil.date()));
        //组合实体类
        BizEvent event = BeanUtil.toBean(eventConfig, BizEvent.class);
        event.setApiLogId(apiLog.getId());
        event.setEventConfigId(eventConfig.getId());
        event.setEventTime(apiLog.getEventTime());
        event.setEventDesc(eventDesc);
        event.setEventAction(EventActionUtil.getEventAction(apiLog.getReqType()));
        bizEventReplaceService.clearBizEvent(event);
        bizEventMapper.insert(event);
    }

    /**
     * 试剂重量大于上次称重
     *
     * @param apiLog
     */
    private void addRecordForReagentWeightThan(BizGoods goods, DevApiLog apiLog) {
        if (StringUtils.isNotBlank(goods.getReagentWeighNeedFlag())) {
            //有上次称重且需要称重
            if (goods.getReagentLastWeigh() != null && goods.getReagentWeighNeedFlag().equals("1")) {
                if (goods.getReagentMaxErrorValue() != null) {
                    //两次差额取绝对值
                    if (NumberUtil.sub(apiLog.getReagentWeight(),goods.getReagentLastWeigh().toString()).compareTo(goods.getReagentMaxErrorValue()) > 0) {
                        //查询对应配置
                        BizEventConfig eventConfig = bizEventConfigMapper.selectById("43");
                        //事件描述
                        String eventDesc = eventConfig.getEventDesc();
                        eventDesc = eventDesc.replace("{{goods}}", bizEventReplaceService.getGoodsNameForEntity(goods));
                        eventDesc = eventDesc.replace("{{last-wt}}", goods.getReagentLastWeigh().toString());
                        eventDesc = eventDesc.replace("{{cur-wt}}", apiLog.getReagentWeight());
                        eventDesc = eventDesc.replace("{{time}}", DateUtil.formatDateTime(DateUtil.date()));
                        //组合实体类
                        BizEvent event = BeanUtil.toBean(eventConfig, BizEvent.class);
                        event.setApiLogId(apiLog.getId());
                        event.setEventConfigId(eventConfig.getId());
                        event.setEventTime(apiLog.getEventTime());
                        event.setEventDesc(eventDesc);
                        event.setGoodsId(goods.getId());
                        event.setEventAction(EventActionUtil.getEventAction(apiLog.getReqType()));
                        bizEventReplaceService.clearBizEvent(event);
                        bizEventMapper.insert(event);

                        //【邮件】借用人+柜门管理员
                        bizEventReplaceService.sendEmailForDoorAdmin(event);
                    }
                }
            }
        }
    }

    /**
     * 报废试剂称重
     *
     * @param apiLog
     */
    private void addRecordForReagentScrap(BizGoods goods, DevApiLog apiLog) {
        //查询对应配置
        BizEventConfig eventConfig = bizEventConfigMapper.selectById("34");
        //事件描述
        String eventDesc = eventConfig.getEventDesc();
        eventDesc = eventDesc.replace("{{goods}}", bizEventReplaceService.getGoodsNameForEntity(goods));
        eventDesc = eventDesc.replace("{{time}}", DateUtil.formatDateTime(DateUtil.date()));
        //组合实体类
        BizEvent event = BeanUtil.toBean(eventConfig, BizEvent.class);
        event.setApiLogId(apiLog.getId());
        event.setEventConfigId(eventConfig.getId());
        event.setEventTime(apiLog.getEventTime());
        event.setEventDesc(eventDesc);
        event.setGoodsId(goods.getId());
        event.setEventAction(EventActionUtil.getEventAction(apiLog.getReqType()));
        bizEventReplaceService.clearBizEvent(event);
        bizEventMapper.insert(event);
    }

    /**
     * 出库称重异常
     *
     * @param apiLog
     */
    private void addRecordForReagentUsageAbn(BizGoods goods, DevApiLog apiLog) {
        //查找未归还的物品台账
        GoodsLedgerPageResult goodsLedgerPageResult = bizGoodsLedgerMapper.getNydRecordForGoodsId(goods.getId());
        if (null != goodsLedgerPageResult) {
            if (null == goodsLedgerPageResult.getReagentOutWeight()) {
                //更新物品取出的重量
                BizGoodsLedger bizGoodsLedger = new BizGoodsLedger();
                bizGoodsLedger.setId(goodsLedgerPageResult.getId());
                bizGoodsLedger.setReagentOutApiId(apiLog.getId());
                String outWeight = apiLog.getReagentWeight();
                if (goods.getReagentContainerWeight() != null) {
                    //有容器重量时候计算毛重
                    outWeight = NumberUtil.round(NumberUtil.sub(outWeight, goods.getReagentContainerWeight().toString()), 2).toString();
                }
                bizGoodsLedger.setReagentOutWeight(outWeight);
                if (goods.getReagentDensity() != null) {
                    bizGoodsLedger.setReagentOutVolume(NumberUtil.div(outWeight, goods.getReagentDensity().toString(), 2).toString());
                }
                bizGoodsLedgerMapper.updateById(bizGoodsLedger);

                if(StringUtils.isNotBlank(goods.getReagentWeighNeedFlag())){
                    //物品需要称重
                    if(goods.getReagentWeighNeedFlag().equals("1")){
                        //出库称重异常
                        if (goods.getReagentMaxErrorValue() != null) {
                            //最后次称重 (优先取最后的称重 否则取初始净重)
                            BigDecimal lastWeight = goods.getReagentLastWeigh() != null ? goods.getReagentLastWeigh() : goods.getReagentInitWeight();
                            if (lastWeight != null) {
                                //两次差额取绝对值
                                if (NumberUtil.sub(lastWeight.toString(), apiLog.getReagentWeight()).abs().compareTo(goods.getReagentMaxErrorValue()) > 0) {
                                    //查询对应配置
                                    BizEventConfig eventConfig = bizEventConfigMapper.selectById("35");
                                    //事件描述
                                    String eventDesc = eventConfig.getEventDesc();
                                    eventDesc = eventDesc.replace("{{goods}}", bizEventReplaceService.getGoodsNameForEntity(goods));
                                    eventDesc = eventDesc.replace("{{time}}", DateUtil.formatDateTime(DateUtil.date()));
                                    eventDesc = eventDesc.replace("{{inv-wt}}", lastWeight.toString());
                                    eventDesc = eventDesc.replace("{{1st-wt}}", apiLog.getReagentWeight());
                                    //组合实体类
                                    BizEvent event = BeanUtil.toBean(eventConfig, BizEvent.class);
                                    event.setApiLogId(apiLog.getId());
                                    event.setEventConfigId(eventConfig.getId());
                                    event.setEventTime(apiLog.getEventTime());
                                    event.setEventDesc(eventDesc);
                                    event.setGoodsId(goods.getId());
                                    event.setEventAction(EventActionUtil.getEventAction(apiLog.getReqType()));
                                    //算借出人的
                                    event.setEventUserId(goodsLedgerPageResult.getDeliveryUserId());
                                    bizEventReplaceService.clearBizEvent(event);
                                    bizEventMapper.insert(event);

                                    //【补全信息】因为仅称重还没柜子信息这里取物品的所属柜子信息
                                    event.setCabinetGroupId(goods.getBioCabinetGroupId());
                                    event.setCabinetId(goods.getBioCabinetId());
                                    event.setCabinetDoorId(goods.getBioCabinetDoorId());
                                    //【邮件】借用人+柜门管理员
                                    bizEventReplaceService.sendEmailForDoorAdmin(event);
                                    bizEventReplaceService.sendEmailForUser(goodsLedgerPageResult.getDeliveryUserId(), event);
                                }
                            }
                        }
                    }
                }

            }
        }
//        if (StringUtils.isNotBlank(goods.getReagentWeighNeedFlag())) {
//            //物品需要称重
//            if (goods.getReagentWeighNeedFlag().equals("1")) {
//                //查找未归还的物品台账
//                GoodsLedgerPageResult goodsLedgerPageResult = bizGoodsLedgerMapper.getNydRecordForGoodsId(goods.getId());
//                if (null != goodsLedgerPageResult) {
//                    //取出重量
//                    if (null != goodsLedgerPageResult.getReagentOutWeight()) {
////                        if (NumberUtil.sub(goodsLedgerPageResult.getReagentOutWeight(), apiLog.getReagentWeight()).compareTo(goods.getReagentMaxErrorValue()) > 0) {
////                            //查询对应配置
////                            BizEventConfig eventConfig = bizEventConfigMapper.selectById("35");
////                            //事件描述
////                            String eventDesc = eventConfig.getEventDesc();
////                            eventDesc = eventDesc.replace("{{goods}}", bizEventReplaceService.getGoodsNameForEntity(goods));
////                            eventDesc = eventDesc.replace("{{time}}", DateUtil.formatDateTime(DateUtil.date()));
////                            eventDesc = eventDesc.replace("{{inv-wt}}", apiLog.getReagentWeight());
////                            eventDesc = eventDesc.replace("{{1st-wt}}", goodsLedgerPageResult.getReagentOutWeight());
////                            //组合实体类
////                            BizEvent event = BeanUtil.toBean(eventConfig, BizEvent.class);
////                            event.setApiLogId(apiLog.getId());
////                            event.setEventConfigId(eventConfig.getId());
////                            event.setEventTime(apiLog.getEventTime());
////                            event.setEventDesc(eventDesc);
////                            event.setGoodsId(goods.getId());
////                            event.setEventAction(EventActionUtil.getEventAction(apiLog.getReqType()));
////                            bizEventReplaceService.clearBizEvent(event);
////                            bizEventMapper.insert(event);
////
////                            //【补全信息】因为仅称重还没柜子信息这里取物品的所属柜子信息
////                            event.setCabinetGroupId(goods.getBioCabinetGroupId());
////                            event.setCabinetId(goods.getBioCabinetId());
////                            event.setCabinetDoorId(goods.getBioCabinetDoorId());
////                            //【邮件】借用人+柜门管理员
////                            bizEventReplaceService.sendEmailForDoorAdmin(event);
////                            bizEventReplaceService.sendEmailForUser(goodsLedgerPageResult.getDeliveryUserId(), event);
////                        }
//                    } else {
//                        //更新物品取出的重量
//                        BizGoodsLedger bizGoodsLedger = new BizGoodsLedger();
//                        bizGoodsLedger.setId(goodsLedgerPageResult.getId());
//                        bizGoodsLedger.setReagentOutApiId(apiLog.getId());
//                        String outWeight = apiLog.getReagentWeight();
//                        if (goods.getReagentContainerWeight() != null) {
//                            //有容器重量时候计算毛重
//                            outWeight = NumberUtil.round(NumberUtil.sub(outWeight, goods.getReagentContainerWeight().toString()), 2).toString();
//                        }
//                        bizGoodsLedger.setReagentOutWeight(outWeight);
//                        if (goods.getReagentDensity() != null) {
//                            bizGoodsLedger.setReagentOutVolume(NumberUtil.div(outWeight, goods.getReagentDensity().toString(), 2).toString());
//                        }
//                        bizGoodsLedgerMapper.updateById(bizGoodsLedger);
//
//
//                    }
//                }
//            }
//        }
    }
}
